import React, { createContext, useContext, useReducer, useEffect, ReactNode } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { ChatMessage } from '../../api/interfaces/qwen';

// 定义会话类型
export interface Conversation {
  id: string;
  title: string;
  messages: ChatMessage[];
  createdAt: number;
  updatedAt: number;
  contextId?: string;
}

// 定义状态类型
interface ConversationState {
  conversations: Conversation[];
  activeConversationId: string | null;
  isLoading: boolean;
  error: Error | null;
}

// 定义操作类型
type ConversationAction =
  | { type: 'SET_CONVERSATIONS'; payload: Conversation[] }
  | { type: 'SET_ACTIVE_CONVERSATION'; payload: string }
  | { type: 'ADD_CONVERSATION'; payload: Conversation }
  | { type: 'UPDATE_CONVERSATION'; payload: Conversation }
  | { type: 'DELETE_CONVERSATION'; payload: string }
  | { type: 'ADD_MESSAGE'; payload: { conversationId: string; message: ChatMessage } }
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'SET_ERROR'; payload: Error | null };

// 创建上下文
interface ConversationContextType {
  state: ConversationState;
  dispatch: React.Dispatch<ConversationAction>;
  // 辅助方法
  createConversation: (title?: string) => Conversation;
  addMessage: (conversationId: string, message: ChatMessage) => void;
  setActiveConversation: (conversationId: string) => void;
  deleteConversation: (conversationId: string) => void;
  clearConversations: () => void;
  getActiveConversation: () => Conversation | null;
}

const ConversationContext = createContext<ConversationContextType | undefined>(undefined);

// 初始状态
const initialState: ConversationState = {
  conversations: [],
  activeConversationId: null,
  isLoading: false,
  error: null,
};

// 存储键名
const STORAGE_KEY = 'qwen_assistant_conversations';

// Reducer 函数
function conversationReducer(state: ConversationState, action: ConversationAction): ConversationState {
  switch (action.type) {
    case 'SET_CONVERSATIONS':
      return {
        ...state,
        conversations: action.payload,
      };
    case 'SET_ACTIVE_CONVERSATION':
      return {
        ...state,
        activeConversationId: action.payload,
      };
    case 'ADD_CONVERSATION':
      return {
        ...state,
        conversations: [action.payload, ...state.conversations],
        activeConversationId: action.payload.id,
      };
    case 'UPDATE_CONVERSATION': {
      const updatedConversations = state.conversations.map((conversation) => 
        conversation.id === action.payload.id ? action.payload : conversation
      );
      return {
        ...state,
        conversations: updatedConversations,
      };
    }
    case 'DELETE_CONVERSATION': {
      const filteredConversations = state.conversations.filter(
        (conversation) => conversation.id !== action.payload
      );
      
      // 如果删除了当前活跃会话，设置新的活跃会话
      const newActiveId = state.activeConversationId === action.payload 
        ? (filteredConversations.length > 0 ? filteredConversations[0].id : null)
        : state.activeConversationId;
        
      return {
        ...state,
        conversations: filteredConversations,
        activeConversationId: newActiveId,
      };
    }
    case 'ADD_MESSAGE': {
      const { conversationId, message } = action.payload;
      const updatedConversations = state.conversations.map((conversation) => {
        if (conversation.id === conversationId) {
          return {
            ...conversation,
            messages: [...conversation.messages, message],
            updatedAt: Date.now(),
            // 如果是第一条用户消息，使用消息内容作为标题
            title: conversation.messages.length === 0 && message.role === 'user' && typeof message.content === 'string'
              ? message.content.substring(0, 40) // 限制标题长度
              : conversation.title,
          };
        }
        return conversation;
      });
      
      return {
        ...state,
        conversations: updatedConversations,
      };
    }
    case 'SET_LOADING':
      return {
        ...state,
        isLoading: action.payload,
      };
    case 'SET_ERROR':
      return {
        ...state,
        error: action.payload,
      };
    default:
      return state;
  }
}

// 上下文提供者组件
interface ConversationProviderProps {
  children: ReactNode;
}

export const ConversationProvider: React.FC<ConversationProviderProps> = ({ children }) => {
  const [state, dispatch] = useReducer(conversationReducer, initialState);

  // 从存储中加载会话
  useEffect(() => {
    const loadConversations = async () => {
      try {
        dispatch({ type: 'SET_LOADING', payload: true });
        
        const storedData = await AsyncStorage.getItem(STORAGE_KEY);
        if (storedData) {
          const { conversations, activeConversationId } = JSON.parse(storedData);
          
          if (Array.isArray(conversations)) {
            dispatch({ type: 'SET_CONVERSATIONS', payload: conversations });
            
            if (activeConversationId && conversations.some(conv => conv.id === activeConversationId)) {
              dispatch({ type: 'SET_ACTIVE_CONVERSATION', payload: activeConversationId });
            } else if (conversations.length > 0) {
              dispatch({ type: 'SET_ACTIVE_CONVERSATION', payload: conversations[0].id });
            }
          }
        }
      } catch (error) {
        dispatch({ 
          type: 'SET_ERROR', 
          payload: error instanceof Error ? error : new Error('加载会话失败') 
        });
      } finally {
        dispatch({ type: 'SET_LOADING', payload: false });
      }
    };

    loadConversations();
  }, []);

  // 当会话状态更改时，存储到本地
  useEffect(() => {
    const saveConversations = async () => {
      try {
        const dataToStore = {
          conversations: state.conversations,
          activeConversationId: state.activeConversationId,
        };
        
        await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(dataToStore));
      } catch (error) {
        console.error('存储会话失败:', error);
      }
    };

    // 仅在会话或活跃会话ID发生变化时保存
    if (state.conversations.length > 0 || state.activeConversationId !== initialState.activeConversationId) {
      saveConversations();
    }
  }, [state.conversations, state.activeConversationId]);

  // 创建新会话
  const createConversation = (title = '新对话') => {
    const newConversation: Conversation = {
      id: `conv_${Date.now()}`,
      title,
      messages: [],
      createdAt: Date.now(),
      updatedAt: Date.now(),
    };
    
    dispatch({ type: 'ADD_CONVERSATION', payload: newConversation });
    return newConversation;
  };

  // 添加消息到会话
  const addMessage = (conversationId: string, message: ChatMessage) => {
    dispatch({
      type: 'ADD_MESSAGE',
      payload: { conversationId, message },
    });
  };

  // 设置活跃会话
  const setActiveConversation = (conversationId: string) => {
    dispatch({ type: 'SET_ACTIVE_CONVERSATION', payload: conversationId });
  };

  // 删除会话
  const deleteConversation = (conversationId: string) => {
    dispatch({ type: 'DELETE_CONVERSATION', payload: conversationId });
  };

  // 清空所有会话
  const clearConversations = () => {
    dispatch({ type: 'SET_CONVERSATIONS', payload: [] });
    dispatch({ type: 'SET_ACTIVE_CONVERSATION', payload: null });
  };

  // 获取当前活跃会话
  const getActiveConversation = (): Conversation | null => {
    if (!state.activeConversationId) return null;
    return state.conversations.find(
      (conversation) => conversation.id === state.activeConversationId
    ) || null;
  };

  const value = {
    state,
    dispatch,
    createConversation,
    addMessage,
    setActiveConversation,
    deleteConversation,
    clearConversations,
    getActiveConversation,
  };

  return (
    <ConversationContext.Provider value={value}>
      {children}
    </ConversationContext.Provider>
  );
};

// 自定义Hook
export const useConversationState = () => {
  const context = useContext(ConversationContext);
  if (context === undefined) {
    throw new Error('useConversationState must be used within a ConversationProvider');
  }
  return context;
};